package com.usermanage.SecurityConfig;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by 過客 on 2018/3/9
 */
@Slf4j
public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

        String url = httpServletRequest.getHeader("Referer");//得到从那个链接过来的
//        String role = SpringSecurityUtils.getCurrentUserrole();
        if ("XMLHttpRequest".equals(httpServletRequest.getHeader("X-Requested-With"))) {
//            if ("ADMINISTRATION".equals(role)){
//                ajaxLoginSuccess(httpServletResponse ,"/index.page");
////                ajaxLoginSuccess(httpServletResponse ,"/administration/index.page/");
//            }else if ("ADMIN".equals(role)){
//                ajaxLoginSuccess(httpServletResponse ,"/admin");
//            }
            ajaxLoginSuccess(httpServletResponse ,"/index/index.page");
        } else {
            redirectStrategy.sendRedirect(httpServletRequest, httpServletResponse, url);
        }
    }
    /**
     * Ajax请求发送Json数据
     *
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void ajaxLoginSuccess(HttpServletResponse response, String url)
            throws IOException {
        //例1：直接返回字符串
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
//        String username = SpringSecurityUtils.getCurrentUsername();
        response.getWriter().println("{\"ok\":1,\"msg\":\"true\",\"url\":\""+url+"\"}");
    }
}
